package com.match;

import com.dao.TableDao;
import com.dao.TableDataDao;
import com.dao.impl.TableDaoImpl;
import com.dao.impl.TableDataDaoImpl;
import com.models.Column;
import com.models.ResultView;
import com.models.Table;
import com.models.TableData;

import java.util.ArrayList;

/**
 * Created by TimeLiar on 2015/10/6.
 * Biu~~Biu~~~Biu~~~~
 */
public class SqlTableMethod {
    private TableDao tableDao;
    private TableDataDao tableDataDao;

    public SqlTableMethod(){
        tableDao = new TableDaoImpl();
        tableDataDao = new TableDataDaoImpl();
    }

    public void createTable(Table table){
        tableDao.add(table);
        tableDataDao.addDate(new TableData(table));
    }

    public ResultView showTables(){
        ResultView view = new ResultView(new String[]{"Name"});
        for(Table table:tableDao.all()){
            view.addRow(new String[]{table.getName()});
        }
        return view;
    }
    public ResultView showData(ArrayList<String[]> rows,String[] columns){
        ResultView view = new ResultView(columns);
        rows.forEach(view::addRow);
        return view;
    }

    public ResultView tableStructure(String tableName){
        Table table = tableDao.getTable(tableName);
        if(table == null){
            System.out.println("table '" + tableName + "' not found");
            return null;
        }
        ResultView resultView = new ResultView(new String[]{"Field","Type","Length","Null","Key"});
        for(Column column:table.getColumns()){
            resultView.addRow(new String[]{column.getName(),
                    column.getType(),
                    String.valueOf(column.getLength()),
                    column.isNotNull()?"No":"YES",
                    column.isPrimaryKey()?"Pri":"No"});
        }
        return resultView;
    }

    public void deleteTable(String tableName){
        tableDao.delete(tableName);
        tableDataDao.deleteDate(tableName);
    }

}
